<?php
namespace soa\finance;
use artisan\cache;
use artisan\db;
use artisan\queue;
use soa\common\RemoteDB;

/**
 * 派费直补
 * Class send_cost
 * @package model
 */
class scan_sign_reward
{
    /**
     * @var string 总部派费直发
     */
    private $queue_key = 'scan_to_sign_reward_money';
    /**
     * @var string 网点派费直发
     */
    private $queue_key_branch = 'scan_to_sign_reward_money:branch';
    private $queue_key_branch_v2 = 'scan_branch_v2:branch';
    /**
     * @var string 个人派费对账
     */
    private $queue_key_person = 'scan_to_sign_reward_money:person';
    /**
     * @var array 辽宁沈阳申通派费直补工号
     */
    private $cm_code_list = array(
        array(
            'money' => 0.3,
            'list' => array('9000008883', '9000008884', '6666667890', '6666660000')
        ),
        array(
            'money' => 0.2,
            'list' => array('1110011089', '1110011070', '1110011004', '1110011033', '1110011080', '1110011027', '1110011031', '1110011051', '1110011085', '1110011005')
        )
    );

    private static $cache_key = 'sto:scan_to_sign:list';

    public function add($data, $branch_name = '')
    {
        if(empty($data) || !is_array($data)){
            return false;
        }
        $data = array_values($data);

        $cm_id = isset($data[0]['cm_id']) ? $data[0]['cm_id'] : 0;
        $cm_code = isset($data[0]['cm_code']) ? $data[0]['cm_code'] : '';
        if(empty($cm_id) || empty($cm_code)){
            return false;
        }
        $branch_no = substr($cm_code, 0, 6);

        $temp_list = array();
        foreach($data as $k => $v){

            $waybill_no = isset($v['waybill_no']) ? trim($v['waybill_no']) : '';
//logDebug($waybill_no,'scan_test');
            if(empty($waybill_no)) continue;

            if(isset($temp_list[$waybill_no])){
                unset($data[$k]);
                continue;
            }else{
                $temp_list[$waybill_no] = 1;
            }

            if($this->filter_waybill_no($waybill_no) == false) {
                //logDebug($waybill_no,'push_waybill_no_filter');
                unset($data[$k]);
                continue;
            }

            $data[$k] = array(
                'courier_id' => $cm_id,
                'courier_code' => $cm_code,
                'brand' => 'sto',
                'waybill_no' => $waybill_no,
                'award_money' => 0,
                'scan_date' => $v['scan_time'],
                'upload_date' => $v['create_time'],
                'branch_no' => $branch_no,
                'branch_name' => ''
            );
        }
        //logDebug($temp_list,'check_push_waybill_no');
//var_dump(count($data));
        $result = $this->getCacheValue($cm_code, $branch_no, 'sto');//var_dump($result);
        $branchRule = $this->getBranchRule($cm_code,'sto');
        $rules=$this->getCacheRule($cm_code,'sto');
        if(isset($result['hq_state']) && $result['hq_state'] == 'on'){
            $this->pushHqList($cm_id, $result['branch_name'], 0.3, $data);
        }
        if(!empty($branchRule)){
            $this->pushBranchListv2($cm_code,$branch_name,$data);
        }

        if(empty($branchRule) && !empty($rules)){
            $shop_name = $branch_name?:$rules[0]['branch_name'];
            $this->pushBranchList($cm_code,$shop_name,$data);
        }

        $award_money = $this->getPersonSetting($cm_id);
        if(!empty($award_money) && is_numeric($award_money)){
            $this->pushPersonList($award_money, $data);
        }
    }

    /**
     * 总部直补
     * @param $courier_id
     * @param $branch_name
     * @param $award_money
     * @param $data
     */
    private function pushHqList($courier_id, $branch_name, $award_money, $data)
    {
//        $count=count($data);
//        $res=$this->check_waybill_num($courier_id, 'hq',$count);
//        if($res == false){
//            logDebug("{$courier_id}".'-超过200票','scan_sign_reward');
//            return;
//        }
        $n=0;
        foreach($data as $v){
            $n++;
            $temp = $v;
            $temp['award_money'] = $award_money;
            $temp['branch_name'] = $branch_name;//var_dump($temp);
            $ivr_isOk=queue::connect('ivr')->push($this->queue_key, serialize($temp));//var_dump($ivr_isOk);
            if(!$ivr_isOk){
                $pda_isOk=queue::connect('pda')->push($this->queue_key, serialize($temp));
                if(!$pda_isOk){
                    logDebug($v['waybill_no'],'scan_sign_3');
                }
            }
            $waybill_no = isset($v['waybill_no']) ? trim($v['waybill_no']) : '';
            $cache_key = 'sto:sign_waybills_no:'.$waybill_no;
            cache::set($cache_key, 1, 604800);
//            if(is_numeric($res)&&!empty($res)){
//                if($n>=$res){
//                    logDebug("{$courier_id}".'-超过200票','scan_sign_reward');
//                    break;
//                }
//            }
        }
    }

    /**网点直补v2
     * @param $cm_code
     * @param $branch_name
     * @param $data
     */
    private function pushBranchListV2($cm_code,$branch_name, $data)
    {
        foreach($data as $v){
            $temp = $v;
            $temp['branch_name']=$branch_name;
            $ivr_isOk=queue::connect('ivr')->push($this->queue_key_branch_v2.$cm_code%5, serialize($temp));
            if(!$ivr_isOk){
                $pda_isOk=queue::connect('pda')->push($this->queue_key_branch_v2.$cm_code%5, serialize($temp));
                if(!$pda_isOk){
                    logDebug($v['waybill_no'],'scan_sign_3_branch');
                }
            }
        }
    }
    /**
     * 网点直补
     * @param $courier_id
     * @param $branch_name
     * @param $award_money
     * @param $data
     */
    private function pushBranchList($cm_code,$branch_name, $data)
    {
//        $count=count($data);
//        $res=$this->check_waybill_num($courier_id, 'branch',$count);
//        if($res == false){
//            logDebug('超过200票','scan_sign_reward');
//            return;
//        }
//        $n=0;
        foreach($data as $v){
            //  $n++;
            $temp = $v;
            $temp['branch_name']=$branch_name;
            $ivr_isOk=queue::connect('ivr')->push($this->queue_key_branch.$cm_code%5, serialize($temp));
            if(!$ivr_isOk){
                $pda_isOk=queue::connect('pda')->push($this->queue_key_branch.$cm_code%5, serialize($temp));
                if(!$pda_isOk){
                    logDebug($v['waybill_no'],'scan_sign_3_branch');
                }
            }
//            $waybill_no = isset($v['waybill_no']) ? trim($v['waybill_no']) : '';
//            $cache_key = 'sto:sign_waybills_no:'.$waybill_no;
//            cache::set($cache_key, 1, 604800);
//            if(is_numeric($res)&&!empty($res)){
//                if($n>=$res){
//                    logDebug('超过200票','scan_sign_reward');
//                    break;
//                }
//            }
        }
    }

    /**
     * 个人对账扫描签收记录
     * @param $award_money
     * @param $data
     */
    private function pushPersonList($award_money, $data)
    {
        foreach($data as $v){
            $temp = $v;
            $temp['award_money'] = $award_money;
            queue::connect('pda')->push($this->queue_key_person, serialize($temp));
        }
    }

    /**
     * 限制单个快递一天内只能奖励200票
     * @param int $courier_id
     * @param string $type
     * @return bool
     */
    private function check_waybill_num($courier_id, $type = 'hq',$count=0)
    {
        $date = date('Ymd');
        if($type == 'hq'){
            $cache_key = "analyse:waybill_no_num:".$date.":".$courier_id;
        }else{
            $cache_key = "analyse:waybill_no_num:branch:".$date.":".$courier_id;
        }
        $num = cache::get($cache_key);
        if(!empty($num) && is_numeric($num)){
            if($num >= 200){
                return false;
            }
            else if($num+$count>=200){
                $n=200-$num;
                cache::incrBy($cache_key,$n);
                return $n;
            }else if($count>1){
                cache::incrBy($cache_key,$count);
                return true;
            }
            cache::incr($cache_key);
            return true;
        }
        cache::set($cache_key, 1, 86400);
        return true;
    }

    /**
     * 过滤一周内重复上传的运单号
     * @param $waybill_no
     * @return bool
     */
    private function filter_waybill_no($waybill_no)
    {
        $cache_key = 'sto:sign_waybills_no:'.$waybill_no;
        $cache_value = cache::get($cache_key);
        if(!empty($cache_value)){
            return false;
        }
        return true;
    }

    /**网点派费v2
     * @param $cm_code
     * @param string $brand
     * @return array|bool|int|mixed
     */
    public function getBranchRule($cm_code,$brand='sto'){
        $cache_key = 'branchrule:courier_no:'.$cm_code.$brand;
        if(!empty($cache_value)){
            if(is_array($cache_value)){
                return $cache_value;
            }
            if($cache_value == 'false'){
                return false;
            }
        }
        $sql = "select * from kdy_scan_branch_user as u INNER JOIN kdy_scan_branch_group as g on g.id=u.group_id where courier_code='{$cm_code}' and u.brand='{$brand}' and g.is_delete='0'  and u.`status`='1'";

        $result = db::connect('finance')->query($sql);
        if(!empty($result) && is_array($result)){
            $data=$result;
            cache::set($cache_key, $data, 300);
            return $data;
        }
        cache::set($cache_key, 'false', 300);
        return false;
    }

    /**
     * 获取网点派费状态
     * @param $cm_code
     * @param $branch_no
     * @param string $brand
     * @return array|bool
     */
    private function getCacheValue($cm_code, $branch_no, $brand = 'sto')
    {
        $cache_key = 'sto:sign_to_sign:branch_no:'.$cm_code;
        $cache_value = cache::get($cache_key);
        if(!empty($cache_value)){
            if(is_array($cache_value)){
                return $cache_value;
            }
            if($cache_value == 'false'){
                return false;
            }
        }
        $result = db::connect('finance')
            ->select('j.*,i.branch_name')
            ->table('kdy_scan_shop_list AS i')
            ->join('kdy_scan_courier_list AS j', 'i.branch_no = j.branch_no', 'INNER JOIN')
            ->getOne(array('i.branch_no' => $branch_no, 'i.brand' => $brand, 'j.courier_code' => $cm_code,'j.rule_shop_id'=>0));
        //$result = db::connect('finance')->table('kdy_scan_courier_list')->getOne(array('branch_no' => $branch_no, 'brand' => $brand, 'courier_code' => $cm_code));
        //$result = db::connect('finance')->table('kdy_scan_shop_list')->getOne(array('branch_no' => $branch_no, 'brand' => $brand));
        //$result = $result['res'];
        if(!empty($result) && is_array($result)){
            $data = array(
                'hq_state' => $result['hq_state'],
                'branch_state' => $result['branch_state'],
                'branch_name' => $result['branch_name']
            );
            cache::set($cache_key, $data, 300);
            return $data;
        }
        cache::set($cache_key, 'false', 300);
        return false;
    }

    public function getCacheRule($cm_code,$brand='sto'){
        $cache_key = $brand.':rule:courier_no:'.$cm_code;
        $cache_value = cache::get($cache_key);//$cache_value='';
        if(!empty($cache_value)){
            if(is_array($cache_value)){
                return $cache_value;
            }
            if($cache_value == 'false'){
                return false;
            }
        }
        $sql = "
        SELECT
	shop.type,
	shop.rule,
	shop.branch_name,
	courier.branch_no,
	set_branch_no
FROM
	kdy_scan_courier_rule AS courier
JOIN kdy_scan_shop_rule AS shop ON courier.rule_id = shop.id
WHERE
	courier_code = '{$cm_code}'
AND courier. STATUS = 0
AND shop. STATUS = 0
AND courier.brand = '{$brand}'
";
        $result = [];
        $result = db::connect('finance')->query($sql);
       // foreach($res as $k=>$v){
          //  $result['branch_name']=$res[0]['branch_name'];
       // }
        if(!empty($result) && is_array($result)){
            $data=$result;
            cache::set($cache_key, $data, 300);
            return $data;
        }
        cache::set($cache_key, 'false', 300);
        return false;
    }

    /**
     * 获取个人派费设置
     * @param $courier_id
     * @return float|bool
     */
    private function getPersonSetting($courier_id)
    {
        $cache_key = 'sign_to_sign:courier_id:'.$courier_id;
        $cache_value = cache::get($cache_key);
        if($cache_value && is_numeric($cache_value)){
            return $cache_value;
        }
        $result = db::connect('finance')->table('kdy_scan_to_sign_setup')->getOne(array('courier_id' => $courier_id));
       // $result = $result['res'];
        if(!empty($result['waybill_money']) && $result['waybill_money'] > 0){
            cache::set($cache_key, $result['waybill_money'], 604800);
            return $result['waybill_money'];
        }
        cache::set($cache_key, 'false', 86400);
        return false;
    }

    public static $db_finance;

    public function getFinanceDB()
    {
        if(empty(self::$db_finance)){
            self::$db_finance = new RemoteDB('finance','kdy_scan_shop_list','finance.core');
        }
        return self::$db_finance;
    }
}


